<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\manager\PlatformManager;
use app\common\manager\UserAccountManager;
use app\common\model\Platform\Log;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户账户管理
 *
 * @icon fa fa-circle-o
 */
class Account extends Backend
{

    /**
     * Account模型对象
     * @var \app\admin\model\user\Account
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Account;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids=null)
    {
        $row = $this->model->where('user_id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($params['total'] > 0){
                $money = bcadd(abs($params['total']),0,2);
                $resultTotal = UserAccountManager::money($row->user_id,$money,UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_SYS_CHANGE,[],false);
                if ($resultTotal['code']!=UserAccountManager::$successCode){
                    throw new Exception($resultTotal['message']);
                }

                $resultPlatform = PlatformManager::platformLog($money,date('Y-m-d H:i:s',time()),Log::DIRECTIVE_OUT,Log::TYPE_SYS_ADJUST,['recipient'=>$row->user_id],false);
                if ($resultPlatform['code']!=PlatformManager::$successCode){
                    throw new Exception($resultPlatform['message']);
                }

            }else if ($params['total'] < 0){
                $money = bcadd(abs($params['total']),0,2);
                $resultTotal = UserAccountManager::money($row->user_id,$money,UserAccountManager::CHANGE_TYPE_PAYMENT,time(),UserAccountManager::TYPE_SYS_CHANGE,[],false);
                if ($resultTotal['code']!=UserAccountManager::$successCode){
                    throw new Exception($resultTotal['message']);
                }

                $resultPlatform = PlatformManager::platformLog($money,date('Y-m-d H:i:s',time()),Log::DIRECTIVE_INCOME,Log::TYPE_SYS_ADJUST,['recipient'=>$row->user_id],false);
                if ($resultPlatform['code']!=PlatformManager::$successCode){
                    throw new Exception($resultPlatform['message']);
                }
            }
            if ($params['score'] > 0){
                $score = bcadd(abs($params['score']),0,2);
                $resultTotal = UserAccountManager::score($row->user_id,$score,UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_SCORE_SYS,[],false);
                if ($resultTotal['code']!=UserAccountManager::$successCode){
                    throw new Exception($resultTotal['message']);
                }
            }else if ($params['score'] < 0){
                $score = bcadd(abs($params['score']),0,2);
                $resultTotal = UserAccountManager::score($row->user_id,$score,UserAccountManager::CHANGE_TYPE_PAYMENT,time(),UserAccountManager::TYPE_SCORE_SYS,[],false);
                if ($resultTotal['code']!=UserAccountManager::$successCode){
                    throw new Exception($resultTotal['message']);
                }
            }
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function show($ids=null)
    {
        $row = $this->model->where('user_id',$ids)->find();
        if (!$row){
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        $this->view->assign('row', $row);
        return $this->view->fetch();

    }

}
